<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            gap: 20px;
        }
        .chat-container {
            flex: 1;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            height: 80vh;
        }
        .users-list {
            width: 250px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 20px;
            cursor: pointer;
        }
        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }
        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 8px;
            background: #f0f2f5;
        }
        .message.system {
            background: #e6f7ff;
            text-align: center;
            color: #1890ff;
        }
        .message.private {
            background: #fff7e6;
            color: #fa8c16;
        }
        .input-area {
            padding: 20px;
            border-top: 1px solid #eee;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .message-input {
            width: 100%;
            min-height: 60px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            font-size: 14px;
            line-height: 1.5;
        }
        .message-input:focus {
            outline: none;
            border-color: #1890ff;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
        }
        .send-button {
            align-self: flex-end;
            padding: 8px 20px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .send-button:hover {
            background: #40a9ff;
        }
        .user-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
        }
        .user-item:hover {
            background: #f0f2f5;
        }
        .connection-status {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px;
            border-radius: 4px;
            background: #ff4d4f;
            color: white;
        }
        .connection-status.connected {
            background: #52c41a;
        }
    </style>
</head>
<body>
    <div class="connection-status">未连接</div>
    <div class="container">
        <div class="chat-container">
            <div class="messages" id="messages"></div>
            <div class="input-area">
                <textarea id="messageInput" class="message-input" placeholder="输入消息..."></textarea>
                <button class="send-button" onclick="sendMessage()">发送</button>
            </div>
        </div>
        <div class="users-list" id="usersList"></div>
    </div>

    <script>
        let ws;
        let username = '';
        let selectedUser = '';

        function connect() {
            // 自动构建 WebSocket 地址
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const host = window.location.host;
            const wsUrl = `${protocol}//${host}/ws`;

            ws = new WebSocket(wsUrl);

            ws.onopen = () => {
                document.querySelector('.connection-status').textContent = '已连接';
                document.querySelector('.connection-status').classList.add('connected');
                promptUsername();
            };

            ws.onclose = () => {
                document.querySelector('.connection-status').textContent = '未连接';
                document.querySelector('.connection-status').classList.remove('connected');
            };

            ws.onmessage = (event) => {
                const message = JSON.parse(event.data);
                console.log('收到消息:', message);  // 添加调试日志
                if (message.type === 'user_list') {
                    updateUserList(message.content.split(','));
                } else if (message.type === 'error') {
                    alert(message.content);
                    promptUsername();  // 重新提示输入用户名
                } else {
                    addMessage(message);
                }
            };
        }

        function promptUsername() {
            username = prompt('请输入您的昵称：');
            if (username) {
                const msg = {
                    type: 'set_username',
                    username: username
                };
                console.log('发送用户名消息:', msg);
                ws.send(JSON.stringify(msg));
            }
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (!message) return;

            ws.send(JSON.stringify({
                type: 'message',
                content: message,
                target: selectedUser
            }));

            input.value = '';
        }

        function updateUserList(users) {
            const usersList = document.getElementById('usersList');
            usersList.innerHTML = '';
            
            usersList.onclick = (e) => {
                if (e.target === usersList) {
                    selectUser('');
                }
            };

            users.forEach(user => {
                if (user) {  // 确保不是空字符串
                    const userItem = document.createElement('div');
                    userItem.className = 'user-item';
                    userItem.textContent = user;
                    userItem.onclick = (e) => {
                        e.stopPropagation();
                        selectUser(user);
                    };
                    usersList.appendChild(userItem);
                }
            });
        }

        function addMessage(message) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message';
            
            // 根据消息类型设置不同的显示格式
            if (message.type === 'system') {
                messageDiv.className += ' system';
                messageDiv.textContent = message.content;
            } else if (message.type === 'private') {
                messageDiv.className += ' private';
                if (message.username === username) {
                    // 自己发送的私聊消息
                    messageDiv.textContent = `[私聊] 你对 ${message.target} 说: ${message.content}`;
                } else if (message.target === username) {
                    // 接收到的私聊消息
                    messageDiv.textContent = `[私聊] ${message.username} 对你说: ${message.content}`;
                } else {
                    // 其他情况（不应该发生）
                    messageDiv.textContent = `[私聊] ${message.username} -> ${message.target}: ${message.content}`;
                }
            } else {
                messageDiv.textContent = `${message.username}: ${message.content}`;
            }
            
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function selectUser(user) {
            selectedUser = user;
            document.querySelectorAll('.user-item').forEach(item => {
                item.style.background = item.textContent === user ? '#e6f7ff' : 'white';
            });
            const input = document.getElementById('messageInput');
            input.placeholder = user ? `发送私聊消息给 ${user}...` : '输入消息...';
        }

        // 页面加载时自动连接
        window.onload = connect;

        // 监听输入框回车事件
        document.getElementById('messageInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html> 